package util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA 加解密工具类
 */
public class RsaUtils {
        /**
         * 生成公私钥
         *
         * @param keySize 密钥长度
         */
        public static Map<String, String> genKeyPair(int keySize) {
            Map<String, String> keyMap = new HashMap<>();
            try {
                //创建密钥对生成器
                KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
                kpg.initialize(keySize);
                //生成密钥对
                KeyPair keyPair = kpg.generateKeyPair();
                //公钥
                PublicKey publicKey = keyPair.getPublic();
                //私钥
                PrivateKey privateKey = keyPair.getPrivate();
                keyMap.put("publicKey", Base64.encodeBase64String(publicKey.getEncoded()));
                keyMap.put("privateKey", Base64.encodeBase64String(privateKey.getEncoded()));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return keyMap;
        }

        /**
         * RSA 加密
         * @param content 待加密字符串
         * @param key     Base64编码的公钥字符串
         */
        public static String rsaEncrypt(String content, String key) {
            byte[] keyBytes = Base64.decodeBase64(key);
            String encryptString = null;
            try {
                X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
                PublicKey pubKey = KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec);
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.ENCRYPT_MODE, pubKey);
                encryptString = Base64.encodeBase64String(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return encryptString;
        }

        /**
         * RSA 解密
         * @param content 待解密Base64字符串
         * @param key     Base64编码的私钥字符串
         */
        public static String rsaDecrypt(String content, String key) {
            byte[] contentBytes = Base64.decodeBase64(content);
            byte[] keyBytes = Base64.decodeBase64(key);
            String decryptString = null;
            try {
                PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
                PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec);
                Cipher cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                decryptString = new String(cipher.doFinal(contentBytes));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return decryptString;
        }

        public static void main(String[] args) {
            Map<String, String> keyMap = genKeyPair(1024);
            System.out.println("公钥======"+keyMap.get("publicKey"));
            System.out.println("私钥======"+keyMap.get("privateKey"));
            String encryptString = rsaEncrypt("测试数据",keyMap.get("publicKey"));
            System.out.println("密文======"+encryptString);
            String decryptString = rsaDecrypt(encryptString,keyMap.get("privateKey"));
            System.out.println("明文======"+decryptString);
        }
}
